package com.github.drinkjava2.gosqlgo;

import com.github.drinkjava2.gosqlgo.util.GsgStrUtils;
import com.github.drinkjava2.gosqlgo.util.TxtUtils;

// GSG imports

@SuppressWarnings("all")
public class JavaSrcBuilder extends SrcBuilder {
	static final ServletTemplate template = GoSqlGoEnv.instance.getJavaTemplate();
	static final Class<?> templateClass = template.getClass();
	public static JavaSrcBuilder instance = new JavaSrcBuilder();

	@Override
	public ServletTemplate getTemplate() {
		return template;
	}

	@Override
	public String createSourceCode(String className, String frontText) {
		SqlJavaPiece piece = SqlJavaPiece.parseFromFrontText(frontText);
		return createSourceCode(className, piece);
	}

	@Override
	public String createSourceCode(String className, SqlJavaPiece piece) {
		String classSrc = TxtUtils.getJavaSourceCodeUTF8(templateClass);
		classSrc = GsgStrUtils.replaceFirst(classSrc, "package " + templateClass.getPackage().getName(),
				"package " + GoSqlGoEnv.instance.getDeploy());

		String classDeclar = GsgStrUtils.substringBetween(classSrc, "public ", "{");
		classSrc = GsgStrUtils.replaceFirst(classSrc, classDeclar,
				"class " + className + " extends " + templateClass.getName());
		classSrc = GsgStrUtils.replaceFirst(classSrc, "// GSG IMPORTS", piece.getImports());
		classSrc = GsgStrUtils.replaceFirst(classSrc, "// GSG TAGS", buildGsgTagsForJavaSourceCode(piece));

		String body = GsgStrUtils.substringBetween(classSrc, "/* GSG JAVA BEGIN */", "/* GSG JAVA END */");

		classSrc = GsgStrUtils.replaceFirst(classSrc, body, piece.getBody());
		return classSrc;
	}

	@Override
	public String createFrontText(SqlJavaPiece piece) {
		String head = buildFrontLeadingTagsAndImports(piece);
		String body = piece.getBody();
		if (head.length() > 0 && body != null && body.length() > 0 && body.charAt(0) == ' ')
			head = head.substring(0, head.length() - 1);
		return head + body;
	}

}
